from datetime import datetime
from flask import render_template, flash, redirect, url_for, request, current_app, jsonify, json
from flask_login import login_required


from .forms import NewTypeForm, EditUserForm, TestForm
from . import admin_bp
from ..models import User, Role, AnonymousUser, Typedict, Codedict
from ..utils import redirect_back, generate_token, validate_token
from ..extensions import db
from ..home.emails import send_confirm_email


@admin_bp.route('/new_user', methods=['GET', 'POST'])
def new_user():
    """新增用户"""
    form = NewTypeForm()
    if form.validate_on_submit():
        name = form.name.data
        email = form.email.data.lower()
        username = form.username.data
        password = form.password.data
        user = User(name=name, email=email, username=username, role_id=1, member_since=datetime.now())
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        # 生成并向邮箱发送验证令牌
        token = generate_token(user=user, operation='confirm')
        # send_confirm_email(user=user, token=token)
        flash('确认邮件已发送，请到您的邮箱查收。', 'info')
        return redirect(url_for('user.login'))
    return render_template('user/new_user.html', form=form)


@admin_bp.route('/test', methods=['GET', 'POST'])
def test():
    """实验内容"""
    form = TestForm()
    return render_template('user/test.html',form=form)


@admin_bp.route('/list_dict', defaults={'page':1}, methods=['GET', 'POST'])
# @admin_bp.route('/list_dict/page/<int:page>', methods=['GET', 'POST'])
# @login_required
def list_dict(page=None):
    """字典类型列表"""
    # form = NewTypeForm()
    if not page:
        page = 1
    page = request.args.get('page', 1, type=int)    # 从查询字符串获取请求页数“第几页”，默认第1页
    per_page = current_app.config['JUDIPLAT_ITEM_PER_PAGE'] # 每页记录数量，默认每页20条数据
    pagination = Typedict.query.order_by(Typedict.id.desc()).paginate(page, per_page=per_page)  # 分页对象
    dicts = pagination.items    # 当前页数的记录列表

    cpagination = Codedict.query.order_by(Codedict.typedict_id.desc()).paginate(page, per_page=per_page)
    codes = cpagination.items
    vdata = "这里有数据了。"
    return render_template('admin/list_dict.html', pagination=pagination, dicts=dicts, cpagination=cpagination, codes=codes, vdata=vdata)

@admin_bp.route('/list_code', defaults={'typeid':1, 'page':1}, methods=['GET', 'POST'])
def list_code(typeid=None, page=None):
    """字典代码列表"""
    if not typeid:
        typeid = 1
    type_id = request.args.get('typeid', 1, type=int)
    if not page:
        page = 1
    page = request.args.get('page', 1, type=int)
    per_page = current_app.config['JUDIPLAT_ITEM_PER_PAGE']
    # pagination = Codedict.query.filter(Codedict.typedict_id=typeid)
    # pagination = Codedict.query.get_or_404(typeid)
    # pagination = Codedict.query.filter(Codedict.typedict_id==type_id).all()     # filter(a==b); filter_by(a=b)
    cpagination = Codedict.query.filter(Codedict.typedict_id == type_id).paginate(page,per_page=per_page)
    codes = cpagination.items
    '''
    # cpages = pagination.paginate(page,per_page=per_page)
    cpages = pagination.items
    chasnext = pagination.has_next
    ctotal = pagination.total
    citer = {}
    for i, item in enumerate(pagination.iter_pages):
        citer[i] = item
    # citer = dict(pagination.iter_pages)
    record = {}
    rdict = {}
    i = 1
    for p in cpages:
        record = {
            "id":p.id,
            "fid":p.typedict_id,
            "name":p.name,
            "isUse":p.isUse
        }
        rdict[i] = record
        i += 1
    # paginate(page, per_page=per_page)
    # codes = pagination.items
    # jcode = pagination.items
    # codes = cpagination.items
    jdata = {
        'typeid':type_id,
        'page':page,
        'per_page':per_page,
        'jcode':rdict,
        'has_next':chasnext,
        'total':ctotal,
        'iter_pages':citer
    }
    # return json.dumps(data, default=lambda o: o.__dict__)
    # return json.dumps(data)
    return jsonify(jdata)
    # return json.dumps(pagination, default=lambda o: o.__dict__)
    '''
    return render_template('admin/list_dict.html', cpagination=cpagination, codes=codes, dicts=None)

@admin_bp.route('/<int:dict_id>/edit_dict', methods=['GET', 'POST'])
def edit_dict(dict_id):
    """编辑用户"""
    form = EditUserForm()
    user = User.query.get_or_404(dict_id)

    if form.validate_on_submit():
        user.name = form.name.data
        user.email = form.email.data.lower()
        user.username = form.username.data
        user.role = form.role.data
        user.active = form.active.data
        db.session.commit()
        flash('修改了这条用户数据。', 'success')
        return redirect(url_for('admin.list_dict', form=form))

    form.name.data = user.name
    form.email.data = user.email
    form.username.data = user.username
    form.role.data = user.role
    form.active.data = user.active
    return render_template('admin/edit_dict.html', form=form)


@admin_bp.route('/<int:dict_id>/delete_dict', methods=['POST'])
def delete_dict(dict_id):
    """删除用户"""
    user = User.query.get_or_404(dict_id)
    db.session.delete(user)
    db.session.commit()
    # flash('删除了一条用户数据。', 'success')
    return redirect(url_for('admin.list_dict'))